package limit;

import com.google.common.util.concurrent.RateLimiter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class Main {

    private static final int LEN = 5;

    private static volatile CountDownLatch countDownLatch = new CountDownLatch(1);
    private static volatile CountDownLatch countDownLatchNon = new CountDownLatch(1);
    private static volatile RateLimiter rateLimiter = RateLimiter.create(1);
    private static volatile RateLimiter rateLimiterNon = RateLimiter.create(1);

    public static void main(String[] args){

        TestThreadNon testThreadNon = new TestThreadNon();
        for(int i=0; i<LEN; ++i) {
            new Thread(testThreadNon).start();
        }

        countDownLatchNon.countDown();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("split");

        TestThread testThread = new TestThread();
        for(int i=0; i<LEN; ++i) {
            new Thread(testThread).start();
        }

        countDownLatch.countDown();

    }

    /**
     * 阻塞
     */
    private static class TestThread implements Runnable{

        @Override
        public void run() {
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            SimpleDateFormat df = new SimpleDateFormat("ss");

            rateLimiter.acquire();
            System.out.println("ok : " + df.format(new Date()));

        }
    }

    /**
     * 非阻塞
     */
    private static class TestThreadNon implements Runnable{

        @Override
        public void run() {
            try {
                countDownLatchNon.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            SimpleDateFormat df = new SimpleDateFormat("ss");

            if(!rateLimiterNon.tryAcquire())
                return;
            System.out.println("ok");

        }
    }


}
